#-*- coding: UTF-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from CtrlUI import CtrlWindowUI
from DriverSerial import DriverSerial

class PySerial(QtGui.QWidget):
    def __init__(self, parent = None): 
        super(PySerial, self).__init__(parent)
        self.cw = CtrlWindowUI()
        self.setSignal()
        self.connect(self.cw.ui.dispTE.qObj, QtCore.SIGNAL('SerialSendData'), self.onSendData)
        self.serialOpend = False
    
    def setSignal(self):
        self.cw.ui.openPB.clicked.connect(self.onChangePort)
        self.cw.ui.clearPB.clicked.connect(self.onClearText)
        
    def onChangePort(self):
        if self.serialOpend:
            self.closePort()
        else:
            self.openPort()
        self.cw.changeOpenButton(self.serialOpend)
        self.cw.setDispTEFocus()
    
    def onClearText(self):
        self.cw.setStatusLBText('onClearText')
        self.cw.setDispTEClear()
        self.cw.getSerialSetting()
        self.cw.setDispTEFocus()
               
    def openPort(self):
        self.ds = DriverSerial()
        self.cw.getSerialSetting()
        self.serialOpend, self.msg = self.ds.open()
        if self.serialOpend:
            self.cw.setStatusLBText('onOpenPort')            
            self.connect(self.ds.qObj, QtCore.SIGNAL('SerialRecvData'), self.onRecvData)
        else:
            self.cw.dispMsgBox('Open serial',
                               '%s%s' % ('Open serial fail!\n', self.msg)
                               )   
        
    def closePort(self):
        self.cw.setStatusLBText('onClosePort')
        if self.serialOpend:
            self.ds.close()
            self.serialOpend = False
        
    def onRecvData(self, data):
        self.cw.setDispTERecv(data)   
                
    def onQuit(self):    
        if self.serialOpend:
            self.ds.close()
       
    def show(self):
        self.cw.show() 
        
    def onSendData(self, data):
        if self.serialOpend:
            self.ds.send(data) 
        else:
            self.cw.dispMsgBox('MySerial',
                               'Serial is not opend!\nPlease open serial first.'
                               ) 
  
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ps = PySerial()    
    ps.show()  
    app.aboutToQuit.connect(ps.onQuit)  
    sys.exit(app.exec_())
